using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

/// <summary>
/// HTTP网络管理器
/// </summary>
public class HttpNetworkManager : MonoBehaviour
{
    // 单例实例
    private static HttpNetworkManager _instance;
    public static HttpNetworkManager Instance
    {
        get
        {
            return _instance;
        }
    }

    // 服务器地址
    [SerializeField] private string serverUrl = "http://localhost:8080";

    void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(gameObject);
            return;
        }

        _instance = this;
        DontDestroyOnLoad(gameObject);
    }

    /// <summary>
    /// 发送POST请求
    /// </summary>
    /// <param name="endpoint">API端点</param>
    /// <param name="jsonData">JSON数据</param>
    /// <param name="callback">回调函数</param>
    public void SendPostRequest(string endpoint, string jsonData, Action<bool, string> callback)
    {
        StartCoroutine(PostRequestCoroutine(endpoint, jsonData, callback));
    }

    /// <summary>
    /// 发送GET请求
    /// </summary>
    /// <param name="endpoint">API端点</param>
    /// <param name="callback">回调函数</param>
    public void SendGetRequest(string endpoint, Action<bool, string> callback)
    {
        StartCoroutine(GetRequestCoroutine(endpoint, callback));
    }

    /// <summary>
    /// POST请求协程
    /// </summary>
    /// <param name="endpoint">API端点</param>
    /// <param name="jsonData">JSON数据</param>
    /// <param name="callback">回调函数</param>
    /// <returns></returns>
    private IEnumerator PostRequestCoroutine(string endpoint, string jsonData, Action<bool, string> callback)
    {
        string url = $"{serverUrl}{endpoint}";
        Debug.Log($"发送POST请求到: {url}, 数据: {jsonData}");

        using (UnityWebRequest request = new UnityWebRequest(url, "POST"))
        {
            byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");

            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log($"POST请求成功: {request.downloadHandler.text}");
                callback?.Invoke(true, request.downloadHandler.text);
            }
            else
            {
                Debug.LogError($"POST请求失败: {request.error}");
                callback?.Invoke(false, request.error);
            }
        }
    }

    /// <summary>
    /// GET请求协程
    /// </summary>
    /// <param name="endpoint">API端点</param>
    /// <param name="callback">回调函数</param>
    /// <returns></returns>
    private IEnumerator GetRequestCoroutine(string endpoint, Action<bool, string> callback)
    {
        string url = $"{serverUrl}{endpoint}";
        Debug.Log($"发送GET请求到: {url}");

        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log($"GET请求成功: {request.downloadHandler.text}");
                callback?.Invoke(true, request.downloadHandler.text);
            }
            else
            {
                Debug.LogError($"GET请求失败: {request.error}");
                callback?.Invoke(false, request.error);
            }
        }
    }
}